package com.yimi.yinhepda.views.moveStock_module.unload;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.MoveStockLoadScanAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.LoadUnloadGroupTableDao;
import com.yimi.yinhepda.db.dao.MoveStockScanMasterTableDao;
import com.yimi.yinhepda.db.dao.MoveStockScanTableDao;
import com.yimi.yinhepda.db.table.LoadUnLoadGroupTable;
import com.yimi.yinhepda.db.table.MoveStockScanMasterTable;
import com.yimi.yinhepda.db.table.MoveStockScanTable;
import com.yimi.yinhepda.db.table.MoveStockTaskCacheTable;
import com.yimi.yinhepda.entity.bean.MoveStockScanChildEntity;
import com.yimi.yinhepda.entity.bean.MoveStockUnloadDetailEntity;
import com.yimi.yinhepda.entity.request.MoveStockFinishTaskRequest;
import com.yimi.yinhepda.entity.request.MoveStockScanRequest;
import com.yimi.yinhepda.entity.request.MoveStockUnloadDetailRequest;
import com.yimi.yinhepda.entity.request.QueryStockNumRequest;
import com.yimi.yinhepda.entity.response.MoveStockUnloadDetailResponse;
import com.yimi.yinhepda.entity.response.QueryStockNumResponse;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.ListUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.SyncHorizontalScrollView;
import com.yimi.yinhepda.utils.ThreadPoolUtils;
import com.yimi.yinhepda.views.load_module.DetailsActivity;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;
import com.yimi.yinhepda.views.unload_module.UnloadCompareActivity;

import org.greenrobot.eventbus.EventBus;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author: lj
 * Date: 2018/12/26
 * Description: 移库卸车扫描界面
 */
public class MoveStockUnloadScanActivity extends BaseActivity implements CommonViewHolder.onItemCommonClickListener {

    /**
     * 票数
     */
    private TextView tvPiaoNum;
    /**
     * 件数
     */
    private TextView tvJianNum;
    /**
     * 实操票数
     */
    private TextView tvRealPiaoNum;
    /**
     * 实操件数
     */
    private TextView tvRealJianNum;
    private TextView tvTitle;

    private RecyclerView mLeftListView;
    private RecyclerView mRightListView;
    /**
     * 横竖联动头容器
     */
    private SyncHorizontalScrollView mTitleHorScv;
    /**
     * 横竖联动内容容器
     */
    private SyncHorizontalScrollView mContentHorScv;

    /**
     * 运单扫描集合
     */
    private List<MoveStockScanMasterTable> mScanEntityList;
    /**
     * 任务号
     */
    private String mTaskNo;

    private MoveStockLoadScanAdapter mLeftAdapter;
    private MoveStockLoadScanAdapter mRightAdapter;
    private String mPlatformNo;
    private String mJoinWrokNum;
    private String mJoinUserName;
    private TextView tvShowDesc;
    private Button btnModifyJoinPeople;
    private MoveStockScanTableDao mScanTableDao;
    private MoveStockScanMasterTableDao mScanMasterTableDao;
    private TextView tvNum;
    private boolean isExit = false;
    public static Handler mHandler;
    public static final int MOVE_STOCK_MANUAL = 100;
    private NetRequest upLoadRequest;
    private boolean isDoing = false;
    /**
     * 移库倒货任务实体，用于移库卸车任务数据传递
     */
    private MoveStockTaskCacheTable moveStockTaskEntity;
    /**
     * 未上传的数据集合
     */
    private List<MoveStockScanTable> mNoUpList;

    public MoveStockUnloadScanActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "移库卸车扫描界面";
    }

    @SuppressLint("HandlerLeak")
    @Override
    protected void onStart() {
        super.onStart();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MOVE_STOCK_MANUAL:
                        //接收手动扫描的运单
                        Bundle data = msg.getData();
                        String result = data.getString("result");
                        doscan(result);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_move_stock_unload_scan);

        initView();
        initData();
    }

    private void initView() {
        tvNum = findViewById(R.id.num);
        tvTitle = findViewById(R.id.title);
        tvShowDesc = findViewById(R.id.tv_showDesc);
        btnModifyJoinPeople = findViewById(R.id.btn_modifyJoinPeople);
        btnModifyJoinPeople.setOnClickListener(this);
        tvPiaoNum = findViewById(R.id.tv_piaoNum);
        tvJianNum = findViewById(R.id.tv_jianNum);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_flash).setOnClickListener(this);
        findViewById(R.id.iv_submit).setOnClickListener(this);
        findViewById(R.id.btn_add).setOnClickListener(this);
        tvRealPiaoNum = findViewById(R.id.tv_realPiaoNum);
        tvRealJianNum = findViewById(R.id.tv_realJianNum);

        mLeftListView = findViewById(R.id.left_container_listview);
        mRightListView = findViewById(R.id.right_container_listview);
        mTitleHorScv = findViewById(R.id.title_horsv);
        mContentHorScv = findViewById(R.id.content_horsv);
    }

    private void initData() {
        tvTitle.setText("移库卸车扫描");
        moveStockTaskEntity = (MoveStockTaskCacheTable) getIntent().getSerializableExtra("CacheTableEntity");
        mTaskNo = moveStockTaskEntity.getTaskNo();

        mTitleHorScv.setScrollView(mContentHorScv);
        mContentHorScv.setScrollView(mTitleHorScv);

        mScanTableDao = new MoveStockScanTableDao();
        mScanMasterTableDao = new MoveStockScanMasterTableDao();

        mScanEntityList = new ArrayList<>();

        mLeftAdapter = new MoveStockLoadScanAdapter(this, mScanEntityList, R.layout.adapter_move_stock_scan_left_item, 1, this);
        mLeftListView.setAdapter(mLeftAdapter);
        mLeftListView.setLayoutManager(new LinearLayoutManager(this));

        mRightAdapter = new MoveStockLoadScanAdapter(this, mScanEntityList, R.layout.adapter_move_stock_scan_right_item, 2, this);
        mRightListView.setAdapter(mRightAdapter);
        mRightListView.setLayoutManager(new LinearLayoutManager(this));

        mLeftListView.setNestedScrollingEnabled(false);
        mRightListView.setNestedScrollingEnabled(false);

        ThreadPoolUtils.execute(new UploadRunnable());

        loadData();
        //获取装卸组信息
        getGroupInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();

        setScanCount();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isExit = true;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_modifyJoinPeople:
                //修改装卸人按钮
                intent = new Intent(this, LoadUnloadGroupActivity.class);
                //扫描类型：1-装车扫描，2=卸车扫描 ,3-离线装车，4-离线卸车,5-移库装车，6-移库卸车，7-单独移库卸车
                intent.putExtra("scanType", 6);
                //装卸车界面跳转过来的类型 ，1-装车，2-卸车,3-离线装车，4-离线卸车,5-移库装车，6-移库卸车，7-单独移库卸车
                intent.putExtra("loadType", 6);
                intent.putExtra("taskNo", mTaskNo);
                intent.putExtra("CacheTableEntity",moveStockTaskEntity);
                startActivity(intent);
                break;
            case R.id.btn_add:
                //手动添加按钮
                intent = new Intent(this, MoveStockUnloadManualAddActivity.class);
                intent.putExtra("taskNo", mTaskNo);
                startActivity(intent);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_flash:
                //刷新按钮
                loadData();
                break;
            case R.id.iv_submit:
                //提交按钮
                submit();
                break;
            default:
                break;
        }
    }

    /**
     * 提交数据
     */
    private void submit() {
        if (mScanEntityList == null || mScanEntityList.isEmpty()) {
            showToast("无运单提交！");
            return;
        }

        showPgDlg("数据查询中...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                mNoUpList = mScanTableDao.findNeedUploadData(mTaskNo, 2);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                if (mNoUpList != null && !mNoUpList.isEmpty()) {
                    showToast("数据还未上传完成，请稍后提交！");
                } else {
                    boolean hasNoScan = false;
                    for (MoveStockScanMasterTable item : mScanEntityList) {
                        for (MoveStockScanChildEntity childItem : item.getChildEntityList()) {
                            if (childItem.getFlag() == 0) {
                                hasNoScan = true;
                                break;
                            }
                        }
                    }
                    String msg;
                    if (hasNoScan) {
                        msg = "有未扫描的运单，是否强制提交？";
                    } else {
                        msg = "是否完成移库装车扫描？";
                    }
                    MyDialog myDialog = new MyDialog(MoveStockUnloadScanActivity.this);
                    myDialog.setIcon(R.drawable.alert);
                    myDialog.setMessage(msg);
                    myDialog.setPositiveClickListener( "是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finishTask();
                        }
                    });
                    myDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "否", null);
                    myDialog.show();
                }
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
                showToast("数据提交异常：" + throwable.toString());
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 上传扫描数据
     */
    private synchronized void uploadData(final UICallBack callBack) {
        final List<MoveStockScanTable> scanTableList = mScanTableDao.findNeedUploadData(mTaskNo, 2);
        if (scanTableList != null && !scanTableList.isEmpty()) {
            MoveStockScanRequest request = new MoveStockScanRequest();
            request.setTaskNo(mTaskNo);
            request.setDeptCode(sharedPreferUtil.getDeptCode());
            request.setDeptName(sharedPreferUtil.getValue(Common.DEPT_NAME));
            request.setCompCode(sharedPreferUtil.getCompanyCode());
            request.setCompName(sharedPreferUtil.getCompanyName());
            request.setPieceNum(mScanEntityList.size());
            request.setOperType(2);
            request.setOperPersonCodes(mJoinWrokNum);
            request.setOperPersonNames(mJoinUserName);
            List<MoveStockScanRequest.TransInventScanVo> transInventScanVoList = new ArrayList<>();
            for (MoveStockScanTable item : scanTableList) {
                MoveStockScanRequest.TransInventScanVo scanVo = new MoveStockScanRequest.TransInventScanVo();
                scanVo.setWaybillNo(item.getWaybillNo());
                scanVo.setChildWaybillNo(item.getChildWaybillNo());
                scanVo.setOperCode(sharedPreferUtil.getValue(Common.USER_CODE));
                scanVo.setOperName(sharedPreferUtil.getEmpName());
                scanVo.setOperTime(item.getOperTime());
                scanVo.setInventAreaCode(item.getInventAreaCode());
                scanVo.setInventAreaName(item.getInventAreaName());
                transInventScanVoList.add(scanVo);
            }
            request.setTransInventScanList(transInventScanVoList);
            isDoing = true;
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(Object.class)
                    .setUrl(Constants.URL_MOVE_STOCK_SCAN)
                    .setRequestObject(request)
                    .setConnTimeOut(5 * 1000)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(final String msg) {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    showToast(msg);
                                }
                            });
                            if (callBack != null) {
                                callBack.onError(msg);
                            }
                            isDoing = false;
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            isDoing = false;
                            //更新扫描数据状态为已上传
                            for (MoveStockScanTable item : scanTableList) {
                                item.setIsUpload(1);
                                try {
                                    mScanTableDao.update(item);
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            }
                            setScanCount();
                            if (callBack != null) {
                                callBack.onSuccess(null);
                            }
                        }
                    });
        } else {
            isDoing = false;
            if (callBack != null) {
                callBack.onSuccess(null);
            }
        }
    }

    /**
     * 完成任务
     */
    private void finishTask() {
        showPgDlg("提交中...");
        MoveStockFinishTaskRequest request = new MoveStockFinishTaskRequest();
        request.setTaskNo(mTaskNo);
        request.setUnloadPiecesNum(Integer.parseInt(tvRealJianNum.getText().toString().trim()));
        request.setUnloadEmpNo(sharedPreferUtil.getValue(Common.USER_CODE));
        request.setUnloadEmpName(sharedPreferUtil.getEmpName());
        request.setOperType(2);
        request.setUnloadPlantformNo(mPlatformNo);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(Object.class)
                .setUrl(Constants.URL_MOVE_STOCK_FINISH_TASK)
                .setRequestObject(request)
                .setConnTimeOut(5 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        SoundVibratorManager.playSound(1);
                        showToast("提交成功！");
                        if (MoveStockUnloadTaskActivity.mHandler != null) {
                            MoveStockUnloadTaskActivity.mHandler.sendEmptyMessage(0);
                        }
                        finish();
                    }
                });
    }

    @Override
    public void onItemClickListener(int position) {
        MoveStockScanMasterTable masterTable = mScanEntityList.get(position);
        Intent intent = new Intent(this, UnloadCompareActivity.class);
        intent.putExtra("operTypeCode", 6);
        intent.putExtra("scanMasterTable", masterTable);
        startActivity(intent);
    }

    @Override
    public void onItemLongClickListener(int position) {
        MoveStockScanMasterTable masterTable = mScanEntityList.get(position);
        Intent intent = new Intent(this, DetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("waybill", masterTable.getWaybillNo());
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == MOVE_STOCK_MANUAL) {
                //移库卸车扫描手动添加

            } else {

            }
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doscan(result);
        }
    }

    private void doscan(String result) {
        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }

        //获取装卸组信息
        getGroupInfo();

        if (mScanEntityList != null && !mScanEntityList.isEmpty()) {
            for (MoveStockScanMasterTable scanEntity : mScanEntityList) {
                if (result.startsWith(scanEntity.getWaybillNo())) {
                    MoveStockScanChildEntity tempChildEntity = null;
                    //查询到相同主单，判断子单是否扫描
                    for (MoveStockScanChildEntity childEntity : scanEntity.getChildEntityList()) {
                        if (result.equals(childEntity.getChildWaybillNo())) {
                            tempChildEntity = childEntity;
                            break;
                        }
                    }
                    if (tempChildEntity == null) {
                        //子单未扫描，添加新的子单进来
                        tempChildEntity = new MoveStockScanChildEntity();
                        tempChildEntity.setWaybillNo(result.substring(0, 12));
                        tempChildEntity.setChildWaybillNo(result);
                        tempChildEntity.setFlag(1);
                        scanEntity.getChildEntityList().add(tempChildEntity);
                    } else if (tempChildEntity.getFlag() == 1) {
                        SoundVibratorManager.playSound(2);
                        showToast("运单已扫描！");
                        return;
                    } else {
                        //子单存在，设置为已扫描状态
                        tempChildEntity.setFlag(1);
                    }

                    //将扫描的数据插入表中
                    MoveStockScanTable scanTable = new MoveStockScanTable(mTaskNo, sharedPreferUtil.getDeptCode(),
                            sharedPreferUtil.getValue(Common.DEPT_NAME), sharedPreferUtil.getCompanyCode(), sharedPreferUtil.getCompanyName(), 2,
                            tempChildEntity.getWaybillNo(), tempChildEntity.getChildWaybillNo(), sharedPreferUtil.getValue(Common.USER_CODE),
                            sharedPreferUtil.getValue(Common.USER_NAME), Constants.GetScanTime(), scanEntity.getMoveInCode(),
                            scanEntity.getMoveInName(), scanEntity.getStockNum(), 0);

                    try {
                        mScanTableDao.insert(scanTable);
                    } catch (SQLException e) {
                        SoundVibratorManager.playSound(2);
                        showToast("保存移库装车数据异常：" + e.toString());
                        return;
                    }

                    mScanEntityList.remove(scanEntity);
                    mScanEntityList = sortList(mScanEntityList);
                    mScanEntityList.add(0, scanEntity);
                    SoundVibratorManager.playSound(1);
                    notifyDataSetChanged();
                    setScanCount();
                    sendMessageToAdd(result);
                    return;
                }
            }
        }
        queryStockNum(result);
    }

    /**
     * 查询库存件数
     */
    private void queryStockNum(final String result) {
        showPgDlg("正在查询数据...");
        QueryStockNumRequest request = new QueryStockNumRequest();
        request.setDeptCode(sharedPreferUtil.getDeptCode());
        request.setTaskNo(mTaskNo);
        request.setOperType(2);
        final String waybillNo = result.substring(0, 12);
        request.setWaybillNo(waybillNo);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryStockNumResponse.class)
                .setUrl(Constants.URL_QUERY_STOCK_NUM)
                .setRequestObject(request)
                .setConnTimeOut(5 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryStockNumResponse response = (QueryStockNumResponse) obj;
                        if (response != null && response.getData() != null) {
                            int stockNum = response.getData().getStockNum();
                            String userCode = sharedPreferUtil.getValue(Common.USER_CODE);
                            //将查询到的库存件数设置到运单中
                            MoveStockScanMasterTable scanEntity = new MoveStockScanMasterTable();
                            scanEntity.setTaskNo(mTaskNo);
                            scanEntity.setOperCode(userCode);
                            scanEntity.setWaybillNo(waybillNo);
                            scanEntity.setMoveOutCode(moveStockTaskEntity.getMoveOutCode());
                            scanEntity.setMoveOutName(moveStockTaskEntity.getMoveOutName());
                            scanEntity.setMoveInCode(moveStockTaskEntity.getMoveInCode());
                            scanEntity.setMoveInName(moveStockTaskEntity.getMoveInName());
                            scanEntity.setStockNum(stockNum);
                            //强扫
                            scanEntity.setIsForceScan(1);
                            //移库卸车
                            scanEntity.setOperType(2);
                            MoveStockScanChildEntity childEntity = new MoveStockScanChildEntity();
                            childEntity.setWaybillNo(waybillNo);
                            childEntity.setChildWaybillNo(result);
                            childEntity.setFlag(1);
                            List<MoveStockScanChildEntity> childList = new ArrayList<>();
                            childList.add(childEntity);
                            scanEntity.setChildEntityList(childList);

                            try {
                                mScanMasterTableDao.insert(scanEntity);
                            } catch (SQLException e) {
                                SoundVibratorManager.playSound(2);
                                showToast("保存移库卸车主单数据异常：" + e.toString());
                                return;
                            }

                            //将扫描的数据插入表中
                            MoveStockScanTable scanTable = new MoveStockScanTable(mTaskNo, sharedPreferUtil.getDeptCode(),
                                    sharedPreferUtil.getValue(Common.DEPT_NAME), sharedPreferUtil.getCompanyCode(), sharedPreferUtil.getCompanyName(), 2,
                                    childEntity.getWaybillNo(), childEntity.getChildWaybillNo(), userCode,
                                    sharedPreferUtil.getValue(Common.USER_NAME), Constants.GetScanTime(), moveStockTaskEntity.getMoveInCode(),
                                    moveStockTaskEntity.getMoveInName(), stockNum, 1);

                            try {
                                mScanTableDao.insert(scanTable);
                            } catch (SQLException e) {
                                SoundVibratorManager.playSound(2);
                                showToast("保存移库卸车子单数据异常：" + e.toString());
                                return;
                            }

                            mScanEntityList = sortList(mScanEntityList);
                            mScanEntityList.add(0, scanEntity);
                            notifyDataSetChanged();
                            SoundVibratorManager.playSound(1);
                            setScanCount();
                            sendMessageToAdd(result);
                        } else {
                            showToast("扫描获取运单为空！");
                        }
                    }
                });
    }

    /**
     * 加载移库卸车数据
     */
    private void loadData() {
        showPgDlg("数据加载中...");
        MoveStockUnloadDetailRequest request = new MoveStockUnloadDetailRequest();
        request.setTaskNo(mTaskNo);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(MoveStockUnloadDetailResponse.class)
                .setUrl(Constants.URL_MOVE_STOCK_QUERY_TASK_DETAIL)
                .setRequestObject(request)
                .setConnTimeOut(5 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        MoveStockUnloadDetailResponse response = (MoveStockUnloadDetailResponse) obj;
                        if (response != null && response.getData() != null) {
                            mScanEntityList.clear();
                            String userCode = sharedPreferUtil.getValue(Common.USER_CODE);
                            List<MoveStockUnloadDetailEntity> detailEntityList = response.getData();
                            for (MoveStockUnloadDetailEntity item : detailEntityList) {
                                MoveStockScanMasterTable scanEntity = new MoveStockScanMasterTable();
                                scanEntity.setTaskNo(mTaskNo);
                                scanEntity.setWaybillNo(item.getWaybillNo());
                                scanEntity.setMoveOutCode(moveStockTaskEntity.getMoveOutCode());
                                scanEntity.setMoveOutName(moveStockTaskEntity.getMoveOutName());
                                scanEntity.setMoveInCode(moveStockTaskEntity.getMoveInCode());
                                scanEntity.setMoveInName(moveStockTaskEntity.getMoveInName());
                                scanEntity.setStockNum(item.getStockNum());
                                List<MoveStockScanChildEntity> childEntityList = new ArrayList<>(0);
                                for (String childItem : item.getChildWaybillNos()) {
                                    MoveStockScanChildEntity childEntity = new MoveStockScanChildEntity();
                                    childEntity.setWaybillNo(item.getWaybillNo());
                                    childEntity.setChildWaybillNo(childItem);
                                    //查询该子单是否已扫描
                                    boolean isExit = mScanTableDao.exitChildWaybillNo(mTaskNo, childItem, 2);
                                    if (isExit) {
                                        childEntity.setFlag(1);
                                    }
                                    childEntityList.add(childEntity);
                                }
                                scanEntity.setChildEntityList(childEntityList);
                                mScanEntityList.add(scanEntity);
                            }
                            /**查询本地强扫的运单**/
                            List<MoveStockScanMasterTable> forceScanList = mScanMasterTableDao.findUnloadForceScanData(mTaskNo, 2, 1);
                            for (MoveStockScanMasterTable item : forceScanList) {
                                MoveStockScanMasterTable scanEntity = new MoveStockScanMasterTable();
                                scanEntity.setTaskNo(mTaskNo);
                                scanEntity.setWaybillNo(item.getWaybillNo());
                                scanEntity.setMoveOutCode(moveStockTaskEntity.getMoveOutCode());
                                scanEntity.setMoveOutName(moveStockTaskEntity.getMoveOutName());
                                scanEntity.setMoveInCode(moveStockTaskEntity.getMoveInCode());
                                scanEntity.setMoveInName(moveStockTaskEntity.getMoveInName());
                                scanEntity.setStockNum(item.getStockNum());
                                //查询本地强扫的子单
                                List<MoveStockScanTable> childList = mScanTableDao.findDataByWaybillNo(mTaskNo, item.getWaybillNo(), 2);
                                List<MoveStockScanChildEntity> childEntityList = new ArrayList<>(0);
                                for (MoveStockScanTable childItem : childList) {
                                    MoveStockScanChildEntity childEntity = new MoveStockScanChildEntity();
                                    childEntity.setWaybillNo(item.getWaybillNo());
                                    childEntity.setChildWaybillNo(childItem.getChildWaybillNo());
                                    childEntity.setFlag(1);
                                    childEntityList.add(childEntity);
                                }
                                scanEntity.setChildEntityList(childEntityList);
                                mScanEntityList.add(scanEntity);
                            }
                            notifyDataSetChanged();
                            SoundVibratorManager.playSound(1);
                            setScanCount();
                        } else {
                            showToast("无移库卸车数据！");
                            SoundVibratorManager.playSound(2);
                        }
                    }
                });
    }

    /**
     * 获取装卸组信息
     */
    private void getGroupInfo() {
        //获取登录的部门类型
        int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (deptType == 5 || deptType == 6) {
            LoadUnLoadGroupTable loadUnLoadGroupTable = new LoadUnloadGroupTableDao().getData();
            if (loadUnLoadGroupTable != null) {
                mPlatformNo = loadUnLoadGroupTable.getPlatform();
            }
            moveStockTaskEntity = (MoveStockTaskCacheTable) getIntent().getSerializableExtra("CacheTableEntity");
            mTaskNo = moveStockTaskEntity.getTaskNo();
            //登录分拨获取装卸组
            mJoinWrokNum = getIntent().getStringExtra("joinWrokNum");
            mJoinUserName = getIntent().getStringExtra("joinUserName");
            if (mJoinWrokNum == null || mJoinUserName != null) {
                LoadUnLoadGroupTable groupTable = new LoadUnloadGroupTableDao().getData();
                mJoinWrokNum = groupTable.getUserCodes();
                mJoinUserName = groupTable.getUserNames();
            }
            if ((mJoinWrokNum == null || mJoinWrokNum.equals("")) && ((mJoinUserName == null) || mJoinUserName.equals(""))) {
                mJoinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
                mJoinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
                if (mJoinUserName == null || mJoinUserName.equals("")) {
                    mJoinUserName = mJoinWrokNum;
                }
            } else if (mJoinUserName == null || mJoinUserName.equals("")) {
                mJoinUserName = mJoinWrokNum;
            }
            tvShowDesc.setVisibility(View.GONE);
            btnModifyJoinPeople.setVisibility(View.VISIBLE);
        } else {
            mJoinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
            mJoinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
            if (mJoinUserName == null || mJoinUserName.equals("")) {
                mJoinUserName = mJoinWrokNum;
            }
        }
        //自动检测没有省区的工号，自动添加上去
        String compCode = sharedPreferUtil.getCompanyCode();
        if (compCode == null || "".equals(compCode)) {
            showToast("企业编码为空！");
        }
        String[] userCodes = mJoinWrokNum.split(",");
        for (int i = 0; i < userCodes.length; i++) {
            String userCode = userCodes[i];
            if (!userCode.contains("@")) {
                userCodes[i] = userCode + "@" + compCode;
            }
        }
        StringBuilder tempUserCodes = new StringBuilder();
        for (String userCode : userCodes) {
            tempUserCodes.append(userCode + ",");
        }
        mJoinWrokNum = tempUserCodes.substring(0, tempUserCodes.length() - 1);
    }

    private void notifyDataSetChanged() {
        mLeftAdapter.notifyDataSetChanged();
        mRightAdapter.notifyDataSetChanged();
    }

    /**
     * 数据排序
     * 一级排序 红>黄>白>绿,getType
     */
    private List<MoveStockScanMasterTable> sortList(List<MoveStockScanMasterTable> list) {
        for (MoveStockScanMasterTable info : list) {
            info.setGetType(info.getType());
        }
        String[] sortNameArr = {"getType"};
        // true升序,false降序
        boolean[] isAscArr = {true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }

    /**
     * 扫描统计设置
     */
    private void setScanCount() {
        //设置未上传数
        List<String> operType = new ArrayList<>(0);
        operType.add("2");
        long count = mScanTableDao.getUnUploadCount(mTaskNo, operType);
        tvNum.setText(count + "");
        EventBus.getDefault().post(new CountEvent((int) count));

        //计算扫描的票和件数
        int totalJian = 0;
        int scanCount = 0;
        for (MoveStockScanMasterTable item : mScanEntityList) {
            for (MoveStockScanChildEntity childItem : item.getChildEntityList()) {
                if (childItem.getFlag() == 1) {
                    scanCount++;
                }
            }
            totalJian += item.getStockNum();
        }

        tvPiaoNum.setText(mScanEntityList.size() + "");
        tvRealPiaoNum.setText(mScanEntityList.size() + "");
        //总件数
        tvJianNum.setText(totalJian + "");
        //未扫描件数
        tvRealJianNum.setText(scanCount + "");
    }

    /**
     * 上传数据的线程
     */
    private class UploadRunnable implements Runnable {
        @Override
        public void run() {
            while (!isExit) {
                if (!isDoing) {
                    uploadData(null);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 发送消息至手动添加界面，刷新界面数据
     */
    private void sendMessageToAdd(String result) {
        if (MoveStockUnloadManualAddActivity.mHandler != null) {
            Bundle data = new Bundle();
            data.putString("result", result);
            Message msg = new Message();
            msg.what = MOVE_STOCK_MANUAL;
            msg.setData(data);
            MoveStockUnloadManualAddActivity.mHandler.sendMessage(msg);
        }
    }
}
